package com.hudilao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hudilao.common.R;
import com.hudilao.dto.SetmealDTO;
import com.hudilao.entity.*;
import com.hudilao.exception.CustomException;
import com.hudilao.mapper.DishMapper;
import com.hudilao.mapper.SetmealDishMapper;
import com.hudilao.mapper.SetmealMapper;
import com.hudilao.service.CategoryService;
import com.hudilao.service.DishService;
import com.hudilao.service.SetmealDishService;
import com.hudilao.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    /**管理端：
     * 新增套餐，同时需要保存套餐和菜品的关联关系
     * @param setmealDTO
     */

    @Transactional
    @Override
    public void saveWithDish(SetmealDTO setmealDTO) {

        // 1. 保存套餐基本信息
        setmealMapper.insert(setmealDTO);

//        for (SetmealDish setmealDish : setmealDTO.getSetmealDishes()) {
//            setmealDish.setId(UUID.randomUUID()); // 或者其他生成唯一 ID 的方式
//        }


        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes().stream().map((item) -> {

            Dish dish = dishMapper.selectById(item.getDishId());

            log.info("---套餐内菜品id---");
            log.info(item.getDishId().toString());

            item.setSetmealId(setmealDTO.getId());

            //item.setPrice(dish.getPrice().multiply(new BigDecimal(item.getCopies())));

            item.setName(dish.getName());

            return item;
        }).collect(Collectors.toList());
        setmealDishes.forEach(System.out::println);
        // 2. 保存套餐和菜品关联信息
        setmealDishMapper.insertBatchSomeColumn(setmealDishes);
    }

    /**管理端：
     * 删除套餐，同时需要删除套餐和菜品的关联数据
     * @param id
     */
    @Transactional
    @Override
    public void removeWithDish(Long id) {

        // 1.删除 setmeal 套餐表数据
        this.removeById(id);

        // 2.删除 setmeal_dish 关系表数据
        LambdaQueryWrapper<SetmealDish> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(SetmealDish::getSetmealId, id);

        setmealDishService.remove(queryWrapper1);

    }

    /**管理端：禁用菜品套餐关联
     * 根据菜品ID查询包含该菜品的套餐列表
     * @param dishId 菜品ID
     * @return 包含该菜品的套餐列表
     */
    @Override
    public List<Setmeal> findByDishId(Long dishId) {

        return setmealMapper.findByDishId(dishId);
    }

    /**管理端：修改套餐状态
     * @param setmeal 套餐
     * @return 修改套餐状态结果
     */
    @Override
    public R<String> updateSetmealStatus(Setmeal setmeal) {
        log.info("更新套餐状态");

        // 查询当前套餐
        Setmeal currentSetmeal = setmealMapper.selectById(setmeal.getId());

        // 套餐不存在
        if (currentSetmeal == null) {
            return R.error("套餐不存在");
        }

        // 更新套餐状态
        int status = setmeal.getStatus() == 0 ? 1 : 0;
        currentSetmeal.setStatus(status);
        log.info("---要修改成的状态：---");
        log.info(String.valueOf(status));

        // 如果请求将套餐状态设置为启用，需要检查所有菜品状态
        if (status == 1) {
            // 查询套餐包含的所有菜品
            List<SetmealDish> setmealDishes = setmealDishService.list(new LambdaQueryWrapper<SetmealDish>()
                    .eq(SetmealDish::getSetmealId, setmeal.getId()));

            // 检查菜品状态
            for (SetmealDish setmealDish : setmealDishes) {
                Dish dish = dishService.getById(setmealDish.getDishId());
                if (dish != null && dish.getStatus() == 0) {  // 0表示菜品处于下架状态
                    log.info("套餐中包含下架菜品，无法启用套餐");
                    return R.error("套餐中包含下架菜品，无法启用套餐");

                }
            }
        }

        // 更新套餐状态
        currentSetmeal.setStatus(status);
        int result = setmealMapper.updateStatusById(currentSetmeal);

        if (result == 0) {
            return R.error("套餐状态更新失败");
        }

        return R.success("套餐状态更新成功");
    }



    //修改套餐及其关联菜品信息
    @Transactional
    @Override
    public void updateWithDish(SetmealDTO setmealDTO) {
        log.info("修改套餐信息及关联菜品信息");

        // 1. 更新套餐基本信息
        setmealMapper.updateById(setmealDTO);

        // 2. 删除原有的套餐和菜品关联信息
        QueryWrapper<SetmealDish> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("setmeal_id", setmealDTO.getId());
        setmealDishService.remove(queryWrapper);

        // 3. 保存新的套餐和菜品关联信息
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();

        setmealDishes.forEach(item -> item.setSetmealId(setmealDTO.getId()));
        //setmealDishService.saveBatch(setmealDishes);
        setmealDishMapper.insertBatchSomeColumn(setmealDishes);
    }


    //查询套餐基本信息
    @Override
    public SetmealDTO getSetmealById(Long id) {
        // 查询套餐基本信息
        Setmeal setmeal = this.getById(id);

        if (setmeal == null) {
            return null;
        }

        SetmealDTO setmealDTO = new SetmealDTO();
        BeanUtils.copyProperties(setmeal, setmealDTO);

        // 查询关联的菜品信息
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();

        //通过id查询
        queryWrapper.eq(SetmealDish::getSetmealId, id);

        //查询套餐与菜品关联关系
        List<SetmealDish> setmealDishes = setmealDishService.list(queryWrapper);

        setmealDishes.forEach(dish -> {
            Dish dishInfo = dishService.getById(dish.getDishId());
            if (dishInfo != null) {
                dish.setName(dishInfo.getName());
            }
        });

        setmealDTO.setSetmealDishes(setmealDishes);

        // 获取分类名称
        Category category = categoryService.getById(setmeal.getCategoryId());
        if (category != null) {
            setmealDTO.setCategoryName(category.getName());
        }

        return setmealDTO;
    }}

